package gogo

import (
	"gogo/workpool"
	"sync"
)

var (
	m_task_sync     sync.Mutex
	m_work_pool_map map[uint64]*workpool.WorkPool
	m_default_max   int = 1
)

func GetTask(task_id uint64) *workpool.WorkPool {
	if m_work_pool_map == nil {
		m_work_pool_map = make(map[uint64]*workpool.WorkPool)
	}

	if cli, ok := m_work_pool_map[task_id]; ok && cli != nil {
		return cli
	}

	InitTask(task_id, m_default_max)
	return m_work_pool_map[task_id]
}

func InitTask(task_id uint64, max int) {
	m_task_sync.Lock()
	defer m_task_sync.Unlock()

	if m_work_pool_map == nil {
		m_work_pool_map = make(map[uint64]*workpool.WorkPool)
	}

	if cli, ok := m_work_pool_map[task_id]; ok && cli != nil {
		return
	}

	m_work_pool_map[task_id] = workpool.NewWorkPool(max)
}

func WaitTask(task_id uint64) {
	if m_work_pool_map != nil {
		if cli, ok := m_work_pool_map[task_id]; ok && cli != nil {
			cli.Wait()
		}
	}
}

func WaitAllTask() {
	if m_work_pool_map != nil {
		for _, cli := range m_work_pool_map {
			if cli != nil {
				cli.Wait()
			}
		}
	}
}
